import { Toast } from "antd-mobile"
import { reqgoodsinfo, reqcartadd } from "../../request/api"
import { getUserInfo } from "./Login"

//状态
const initState ={
    info: {}
}

//actionType
const TYPES={
    DETAIL_CHANGE_INFO: "DETAIL_CHANGE_INFO"
}

//修改state reducer
const reducer = (state=initState,action)=>{
    switch(action.type){
        case TYPES.DETAIL_CHANGE_INFO:
            return {
                ...state,
                info:action.info
            }
        default:
            return state;
    }
}

//逻辑和异步actions actionCreators
export const actions={
    changeInfo:info=>({type:TYPES.DETAIL_CHANGE_INFO,info}),
    
    requestInfo:(id)=>(dispatch,getState)=>{
        reqgoodsinfo({id}).then(d=>{
            let info = d.data.list[0]
            // info.specsattr = info.specsattr.split(",")
            dispatch(actions.changeInfo(info))
        })
    },

    addshop:()=>(dispatch,getState)=>{
        let userInfo=getUserInfo(getState())
        let info = getInfo(getState())
        reqcartadd({
            uid: userInfo.uid,
            goodsid: info.id,
            num: 1,        
        }).then(d=>{
            if(d.data.code===200){
                Toast.show({
                    content:d.data.msg
                })
            }
        })
    }
}

//导出数据 Selectors
export const getInfo=state=>state.Detail.info

//导出reduer
export default reducer;